import mongoose from "mongoose";
const { Schema, model } = mongoose;
export function createModel(doc, schema, plugins = []) {
  const sche = new Schema(schema);
  sche.plugin(commonPlugin);
  plugins.forEach((p) => {
    sche.plugin(p);
  });

  return model(doc, sche);
}

function commonPlugin(schema, options) {
  schema.add({ updated_at: { type: Date, default: Date.now } });
  schema.add({ created_at: { type: Date, default: Date.now } });

  schema.pre("save", function (next) {
    if (!this.created_at) {
      this.created_at = new Date();
    }
    this.updated_at = new Date();
    next();
  });
  schema.pre("find", function (next) {
    this.select("-__v");
    next();
  });
}
